package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.FileSystemReader;
import com.example.demo.common.Result;
import com.example.demo.dto.Gkpaper.GkpaperAddRequest;
import com.example.demo.dto.Gkpaper.GkpaperQueryRequest;
import com.example.demo.entity.Gkhomework;
import com.example.demo.entity.Gkpaper;
import com.example.demo.service.GkpaperService;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/gkpaper")
public class GkpaperController {

    @Resource
    private GkpaperService gkpaperService;

    @PostMapping("/list/page")
    public Result listGkpaperByPage(@RequestBody GkpaperQueryRequest gkpaperQueryRequest) {
        long current = gkpaperQueryRequest.getCurrent();
        long size = gkpaperQueryRequest.getPageSize();
        // 查询数据库
        Page<Gkpaper> gkpaperPage = gkpaperService.page(new Page<>(current, size),
                gkpaperService.getQueryWrapper(gkpaperQueryRequest));

        return Result.success(gkpaperPage);
    }

    @PostMapping("/add")
    public Result addGkpaper(
            @RequestParam("file") MultipartFile file,
            @ModelAttribute GkpaperAddRequest gkpaperAddRequest)
    {
        boolean addgkpaper = gkpaperService.addgkpaper(file, gkpaperAddRequest);
        return addgkpaper ? Result.success("添加成功") : Result.error("添加失败");
    }

    @DeleteMapping("/delete")
    public Result deleteGkpaper(Integer id ){
        //查出来
        Gkpaper gkpaper = gkpaperService.getById(id);
        if (gkpaper == null){
            return Result.error("不存在");
        }
        String filepath = gkpaper.getFile();
        String currentPath = System.getProperty("user.dir");
        if (filepath != null){
            //删除文件
            File file= new File(currentPath + filepath);
            file.delete();
        }
        boolean b = gkpaperService.removeById(id);
        return b ? Result.success("删除成功") : Result.error("删除失败");
    }
    @PostMapping("/edit")
    public Result editGkpaper(  @RequestParam(value = "file", required = false) MultipartFile file,
                                @ModelAttribute GkpaperAddRequest gkpaperAddRequest) {
        Gkpaper gkpaper = new Gkpaper();
        BeanUtils.copyProperties(gkpaperAddRequest, gkpaper);
        if (file != null) {
            String originalFilename = file.getOriginalFilename();
            String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String currentPath = System.getProperty("user.dir");
            String filePath = currentPath + "/gkpaper/" + newFileName;
            //将文件保存到指定路径
            try {
                file.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //删除旧文件
            if (gkpaper.getFile() != null){
                String filepath = gkpaper.getFile();
                if (filepath != null){
                    //删除文件
                    File file1= new File(currentPath + filepath);
                    file1.delete();
                }
            }

            //设置新的文件路径
            gkpaper.setFile("/gkpaper/"+newFileName);

        }
        boolean b = gkpaperService.updateById(gkpaper);
        return b ? Result.success("修改成功") : Result.error("修改失败");
    }
    @GetMapping("/get")
    public Result getGkpaper( GkpaperQueryRequest gkpaperQueryRequest){
        long current = gkpaperQueryRequest.getCurrent();
        long size = gkpaperQueryRequest.getPageSize();
        Page<Gkpaper> gkpaperPage = gkpaperService.page(new Page<>(current, size),
                gkpaperService.getQueryWrapper(gkpaperQueryRequest));
        return Result.success(gkpaperPage);
    }
    @GetMapping("/preview/{filename:.+}")
    public Result previewFile(@PathVariable String filename) {
        String currentPath = System.getProperty("user.dir");
        String filePath = currentPath + "/gkpaper/" + filename;
        File file = new File(filePath);
        if (file.exists()) {
            // 文件存在，返回文件内容
            try {
                String content = FileSystemReader.readFileFromSystem(filePath);
                return Result.success(content);
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("文件读取失败");
            }
        } else {
            // 文件不存在，返回错误信息
            return Result.error("文件不存在");
        }
    }



    @GetMapping("/download/{id}")
    public ResponseEntity<org.springframework.core.io.Resource> downloadFile(@PathVariable Integer id) {
        // 1. 查询文件信息
        Gkpaper gkpaper = gkpaperService.getById(id);
        if (gkpaper == null) {
            return ResponseEntity.notFound().build();
        }

        // 2. 检查文件路径
        String filePath = gkpaper.getFile();
        if (filePath == null || filePath.isEmpty()) {
            return ResponseEntity.badRequest().build();
        }

        try {
            // 3. 构建完整文件路径
            Path fullPath = Paths.get(System.getProperty("user.dir"), filePath);

            // 4. 检查文件是否存在
            if (!Files.exists(fullPath)) {
                return ResponseEntity.notFound().build();
            }

            // 5. 创建资源对象
            org.springframework.core.io.Resource resource = new UrlResource(fullPath.toUri());

            // 6. 从文件路径中提取文件名
            String filename = filePath.substring(filePath.lastIndexOf('/') + 1);

            // 7. 设置响应头
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + filename + "\"")
                    .contentType(MediaType.parseMediaType(
                            Files.probeContentType(fullPath)))
                    .body(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }









}
